<template>
  <div class="article-meta">
    <nuxt-link :to="{
      name: 'profile',
      params: {
        username: article.author.username
      }
    }">
      <img :src="article.author.image" />
    </nuxt-link>
    <div class="info">
      <nuxt-link class="author" :to="{
        name: 'profile',
        params: {
          username: article.author.username
        }
      }">
        {{ article.author.username }}
      </nuxt-link>
      <span class="date">
        {{ article.createdAt | date('MMM DD, YYYY') }}
      </span>
    </div>
    <span v-if="!isAuthor">
      <button
        class="btn btn-sm btn-outline-secondary"
        v-if="isAuthor" 
        :class="{
          active: article.author.following
        }"
      >
        <i class="ion-plus-round"></i>
        &nbsp;
        Follow {{ article.author.username }}
      </button>
      &nbsp;&nbsp;
      <button
        class="btn btn-sm btn-outline-primary"
        :class="{
          active: article.favorited
        }"
      >
        <i class="ion-heart"></i>
        &nbsp;
        Favorite Article <span class="counter">({{ article.favoritesCount }})</span>
      </button>
    </span>
    <span v-else>
      <nuxt-link
        class="btn btn-outline-secondary btn-sm"
        ui-sref="app.editor({ slug: $ctrl.article.slug })"
        :to="{
          name: 'editor-article',
          params: {
            slug: article.slug
          }
        }">
        <i class="ion-edit"></i> Edit Article
      </nuxt-link>
      <button class="btn btn-outline-danger btn-sm" @click="onDeleteArticle">
        <i class="ion-trash-a"></i> Delete Article
      </button>
    </span>
  </div>
</template>

<script>
import {
  mapState
} from 'vuex'
import { deleteArticle } from '@/api/article'
export default {
  name: 'ArticleMeta',
  props: {
    article: {
      type: Object,
      required: true
    }
  },
  computed: {
    ...mapState(['user']),
    isAuthor() {
      if (!this.user) {
        return false
      }
      return this.article.author.username === this.user.username
    }
  },
  methods: {
    async onDeleteArticle() {
      await deleteArticle(this.article.slug)
      this.$router.go(-1)
    }
  }
}
</script>

<style>

</style>